<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

	/**
	 * @author Garry Willits
	 * @copyright 
	 * @date 10th May 2011
	 */
class EditImage  extends CI_Controller  {
	
	/**
	 * Used to identify which category we are in though really superflous
	 * @var int
	 */
	protected $cat_id;
	
	/**
	 * Used to identify where in pagination we have come from
	 * @var int 
	 */
	protected $page_num;
	
	public function __construct( $id,$c_id,$p_num)
	{   
		parent::__construct();
		$this->cat_id = $c_id;
		$this->page_num = $p_num;
		$this->load->database();
		$this->display = new Display();
		$this->load->database();
		$this->load->helper('url');
		$this->load->library('form_validation');
		$this->load->library('encrypt');
		$this->load->helper(array('form', 'url','path','file'));
		$this->load->library('form_validation');
		$this->load->helper('Utils');
		$this->load->model('GalleryModel','gmodel');
		$this->display->scripts = 'jquery.js';
		$this->display->scripts = 'jquery-ui.js';
		$this->display->scripts = 'lightbox.js';
		$this->display->scripts = 'uiinit.js';
		$this->display->styles = 'ui';
		$this->display->styles = 'themes/smoothness/jquery.ui.all';
		$this->display->styles = 'lightbox';
		$this->display->styles = 'common';
		$upload = $this->input->post('upload_submitted');
		$this->display->errors = null;
		$query = $this->gmodel->getCategories();
		$imagequery = $this->gmodel->getImage($id);
		$categoryquery = $this->gmodel->getCategoryById( $imagequery->category_id );
		$cancel =$this->input->post('cancel');
		if(!empty($cancel)){
			redirect('/admin/images/catId/'.$this->cat_id."/page/".$this->page_num);
		}
		$del = $this->input->post('delete');
		$pathdetails = $this->getFile($imagequery->location);
		if( !empty( $del ) ){
			
			recursiveDelete($pathdetails['dir'], $pathdetails['filename']);
			$this->gmodel->deleteImage($imagequery->id);
			redirect('/admin/images/catId/'.$this->cat_id."/page/0");
		}
			$this->category_options = array();
			foreach ($query as $row)
			{
			   $this->category_options[ $row->id ]= $row->name;
			}
			$this->load->library('form_validation');
			$this->form_validation->set_rules('title', 'Title', 'trim|required|min_length[2]|max_length[40]|xss_clean');
			$this->form_validation->set_rules('description', 'Description', 'trim|xss_clean');
			$this->form_validation->set_rules('short_description', 'short_Description', 'trim|xss_clean');
			//$this->form_validation->set_rules('date_created', 'Date Created', 'trim|xss_clean');
			$this->form_validation->set_rules('date_created', 'Date', 'callback_validateDate');
			$this->form_validation->set_rules('new_cat', 'New Category', 'trim|xss_clean|callback_validateCategory');
			$this->form_validation->set_rules('price', 'Price', 'numeric|trim|xss_clean');
			$this->display->imgdata = array();
			
			if ($this->form_validation->run() == FALSE)
			{
				$this->display->errors = $this->form_validation->_error_fields;
			}
			else {
				
				$date = $this->input->post('date_created');
				if( $date!=""){
					$dayofmonth = substr($date,0,2);
					$month = substr($date,3,2);
					$year = substr($date,6,4);
					$date_format = "$year-$dayofmonth-$month";
				}
				else {
					$date_format=NULL;
				}
				$category_id=0;
				$cat_name = "";
				$new_cat = $this->input->post('new_cat');
				if( !empty( $new_cat ) ){
					$cat_name = $new_cat;
					// check to see if we need to create a directory
					if ( !get_file_info( "images/".$cat_name)  ){ // check if Client directory exists if not CREATE IT
			            mkdir( set_realpath("images/".$cat_name) , DIR_WRITE_MODE);
			        }
					$category_id=$this->gmodel->newCategory($cat_name);
				}
				else {
					$category_id = $this->input->post('categories');
					$cat_name = $this->category_options[ $category_id ];
					// move the image to new category
					if($category_id!= $imagequery->category_id ){
						$newfile = "images/$cat_name/".$pathdetails['filename'];
						if( is_file($newfile)){
						unlink($newfile);
						}
						rename($imagequery->location,$newfile);
						recursiveDelete($pathdetails['dir'], $pathdetails['filename']);
						$imagequery->location = $newfile;
					}
				}
				$this->gmodel->updateImage($imagequery->id,$imagequery->location,$this->input->post('title'),$this->input->post('description'),$this->input->post('short_description'),$category_id );
				// get out of here
				redirect('/admin/images/catId/'.$this->cat_id."/page/".$this->page_num);
			} 
			
		// display stuff
		if(empty($category_id) ){
			$category_id = $categoryquery->id;
		}
		$this->display->options = $this->category_options;
		$this->display->catid = $category_id;
		$this->display->imagequery = $imagequery;
		$this->display->base = "imageAdmin/processImages3";
		$img =new Image($imagequery->location, (int)120,$imagequery->width,$imagequery->height);
		$img->finalize();
		$wrapper = new ControlImageWrapper($imagequery->title);
		$wrapper->addChild($img);
		$wrapper->title = $imagequery->title;
		$wrapper->id = "img$imagequery->id";
		$wrapper->finalize();
		$this->display->addChild($wrapper); 
		$this->display->previewpath = $imagequery->location;
		$this->display->submitpath = current_url();
		$this->display->finalize();
	}
	/**
	 * 
	 * validates this string as uk date
	 * @param string $datein
	 */
	public function validateDate( $datein ){
		if( $datein == '' )return true;
		$valid = false;
		$arr=split("/",$datein); // splitting the array
		if( count( $arr ) == 3 ){
			$mm=$arr[0]; // first element of the array is month
			$dd=$arr[1]; // second element is date
			$yy=substr ($arr[2],2); // third element is year
			If(checkdate($mm,$dd,$yy)){
				$valid = true;
			}
		}
		if( !$valid ){
			$this->form_validation->set_message('validateDate', '%s  must be in the date format dd/mm/yy');
		}
		return $valid ;
	}
	/**
	 * 
	 * Checks to see this category doesn't exist
	 * @param unknown_type $category
	 */
	public function validateCategory( $category ){
		if ($this->gmodel->checkGalleryExists($category)){
			$this->form_validation->set_message('validateCategory', "The category $category already exists!");
			return false;
		}
		return true;
	}
	
	/**
	 * gets a file and directory from an url string
	 * @return array 
	 */
	protected function getFile($path){
			$pathdetails = explode('/',$path);
			$file = array_pop($pathdetails);
			$dirpath =implode(DIRECTORY_SEPARATOR,$pathdetails);
			return array('dir'=>$dirpath,'filename'=>$file);
	}
}
